package com.tfswx.jkgl.core.autoconfigure;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

/**
 * @author ricky
 * @date 2021/12/8
 */
@Slf4j
public class ConfEnvironmentPostProcessor implements EnvironmentPostProcessor {
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        // File file = ResourceUtils.getFile("classpath:jkgl.properties");
        // Properties defaultProperties = loadProperties(file);
        Properties defaultProperties = new Properties();
        defaultProperties.setProperty("mybatis-plus.configuration.call-setters-on-nulls", "true");
        // Properties applicationProperties = loadProperties(ResourceUtils.getFile("classpath:application.properties"));

        MutablePropertySources propertySources = environment.getPropertySources();
        propertySources.addFirst(new PropertiesPropertySource("application.properties", defaultProperties));
        System.out.println("加载默认配置");
    }

    /**
     * 加载配置文件
     *
     * @param f
     * @return
     * @throws IOException
     */
    private Properties loadProperties(File f) throws IOException {
        FileSystemResource resource = new FileSystemResource(f);
        return PropertiesLoaderUtils.loadProperties(resource);
    }

    /**
     * 获取当前项目的根路径
     *
     * @return
     * @throws IOException
     */
    private String getRootPath() throws IOException {
        File rootFile = new File("");
        String rootPath = rootFile.getCanonicalPath();
        return StringUtils.substring(rootPath, 0, StringUtils.lastIndexOf(rootPath, File.separator));
    }
}
